<?php
/**
 * Created by PhpStorm.
 * User: 牛赞赞
 * Date: 2021/1/23
 * Time: 11:34
 */

namespace App\Middleware;

use App\Model\UserToken;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $token = $this->request->getHeader('token');
        if(empty($token)){
            return $this->response->json(
                [
                    'code' => 0,
                    'msg'  => '缺少Token',
                    'data' => [],
                ]
            );
        }
        $con = UserToken::checkUser($token[0]);
        if($con['code'] !==0){
            return $this->response->json(
                [
                    'code' => 0,
                    'msg'  => $con['msg'],
                    'data' => [],
                ]
            );
        }
        return $handler->handle($request);
    }
}